package controllers;

import play.*;
import play.mvc.*;

import java.util.*;

import models.*;

public class Application extends Controller {

      @Before(unless={"login", "authenticate", "logout"})
    static void checkUser() throws Throwable { 
           renderArgs.put("connected", connectedUser());
            User user=connectedUser(); 
            flash.put("yurl", request.method == "GET" ? request.url : "/");
        if (connectedUser() == null) {            	
        	login();
        } else {     	
        }
    }
        
    public static void index() {
        render();
            
    }
    
    public static void authenticate(String name, String password) throws Throwable {
		User user = User.findByName(name);
        
        if (!authUser(user, name, password)){        	
        	params.flash();
        	login();
        }
        connect(user);
        redirectToOriginalURL();
    }

    public static void login() {
    	flash.keep("yurl");
        render();
    }

    public static void logout() {
    	flash.success("You've been logged out");
    	session.clear();
    	index();
    }

    private static void connect(User user) {
        session.put("logged", user.id);
        //session.put("role", user.role.id);
        user.lastLoginTime  = new Date();
        user.save();
    }
    
    static User connectedUser() {
        String userId = session.get("logged");
        return (userId==null) ? null : (User)User.findById(Long.parseLong(userId));
    }
    
    static void redirectToOriginalURL() throws Throwable {       
        String url = flash.get("yurl");
        if(url == null) {
            url = "/";
        }
        redirect(url);
    }
    
    public static boolean authUser(User user, String name, String password) {    	
		boolean authentic = true;

		flash.keep("yurl");	
		if (user == null) {
        	flash.error("你的用户名不存在，请重新输入用户名。");
        	authentic = false;
        } else {
        	if (!user.checkPassword(password)) {    	
        		flash.error("你的用户名和密码不符，请再试一次。");
        		authentic =false;
        	}
        }
        if (!authentic) flash.put("name", name);                 
        return authentic;
	}
    
	public static void changePassword(String curPassword, String password, String password2) {
		User user = connectedUser(); 
		if (!user.checkPassword(curPassword)) {
			renderText("当前密码输入错误！");
		} else {
			if (password.length()<6) renderText("密码不能小于6个字符，请输入符合规则的密码！");
            if (password.length()>16) renderText("密码不能大于16个字符，请输入符合规则的密码！");
            
            if (!password.equals(password2)) renderText("两次输入的密码不一致，请重新输入密码！");
            
			user.changePassWord(password);
			user.save();
		}
		renderText("修改密码成功！");
	}

}